package com.haoshuang.zhouzhoubang.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityAppointmentCustomer2Binding
import com.haoshuang.zhouzhoubang.model.bean.OrderDetail2Bean
import com.haoshuang.zhouzhoubang.model.bean.TimeBean8
import com.haoshuang.zhouzhoubang.model.bean.YyBean
import com.haoshuang.zhouzhoubang.model.event.TransferOrderSuccess
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowServiceItemDialog
import com.haoshuang.zhouzhoubang.ui.dialog.Tx3Dialog
import com.haoshuang.zhouzhoubang.ui.page.order.assignment.TaskAssignmentActivity
import com.haoshuang.zhouzhoubang.ui.page.order.rework.rework.team.TeamListAdapter
import com.haoshuang.zhouzhoubang.ui.page.order.time.UpdateServiceTimeActivity
import com.haoshuang.zhouzhoubang.ui.vm.AppointmentCustomerViewModel2
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemChildClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.callPhone
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import java.text.DecimalFormat

/**
 *
 */
class AppointmentCustomerActivity2 :
    BaseVMActivity<AppointmentCustomerViewModel2, ActivityAppointmentCustomer2Binding>() {

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.ivBack.click { finish() }
        binding.appBar.tvTitle.text = "预约客户"
    }

    private var yyBean: YyBean? = null

    /// 订单详情
    private var orderDetailBean: OrderDetail2Bean? = null
    var list = arrayListOf<TimeBean8.Timer>()
    var list2 = arrayListOf<TimeBean8>()
    var list3 = arrayListOf<YyBean.ThirdInfo.TeamUser>()
    var service_day = ""
    var service_time = ""

    lateinit var adapter3: TeamListAdapter
    var ids = 0
    override fun onRestart() {
        super.onRestart()
        vm.getData("id" to ids)
        vm.getOrderDetail("id" to ids)
    }

    var user_status = ""
    var gson = Gson()

    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {
        ids = intent.getIntExtra("ids", 0)
        user_status = intent.getStringExtra("user_status").toString()

        XPopup.Builder(this).asCustom(Tx3Dialog(this) {}).show()
        binding.apply {

            val lay = LinearLayoutManager(this@AppointmentCustomerActivity2)
            val lay2 = LinearLayoutManager(this@AppointmentCustomerActivity2)
            lay2.orientation = LinearLayoutManager.HORIZONTAL
            lay.orientation = LinearLayoutManager.HORIZONTAL

            rvList3.layoutManager = lay2


            adapter3 = TeamListAdapter(list3)
            llAdd.clickWithTrigger {
                var str = gson.toJson(list6)
                startPage<TaskAssignmentActivity>(
                    "ids" to ids.toString(),
                    "user_id9" to user_id9,
                    "bean" to str,
                    "isPersonal" to false
                )
            }

            rvList3.adapter = adapter3

            callPhone.clickWithTrigger {
                if (user_phone.isNullOrBlank()) {
                    toast("电话不能为空")
                    return@clickWithTrigger
                }

                callPhone(user_phone)
            }
            adapter3.setOnItemChildClick(id = R.id.callPhone) { view, position, item ->
                if (item == null) return@setOnItemChildClick
                if (list3[position].phone.isNullOrBlank()) {
                    toast("电话不能为空")
                } else {
                    callPhone(list3[position].phone)
                }
            }
            adapter3.setOnItemChildClick(id = R.id.tvAdd) { view, position, item ->
                if (item == null) return@setOnItemChildClick
                var str = gson.toJson(list6)
                startPage<TaskAssignmentActivity>(
                    "ids" to ids.toString(), "user_id9" to user_id9, "bean" to str
                )
            }

            tvUpdateTime.clickWithTrigger {
                startPageForResult<UpdateServiceTimeActivity>("cate_id" to cate_id) { code, data ->
                    if (code == Activity.RESULT_OK) {
                        if (data != null) {
                            service_day = data.getStringExtra("service_day").toString()
                            val service_day1 = data.getStringExtra("service_day1")
                            service_time = data.getStringExtra("service_time").toString()
                            binding.tvTime.text = "$service_day1     $service_time"
                        }
                    }
                }
            }
            callPhone2.clickWithTrigger {
                if (user_phone2.isNullOrBlank()) {
                    toast("电话不能为空")
                    return@clickWithTrigger
                }
                callPhone(user_phone2)
            }
            tvCommit.clickWithTrigger {
                if (service_day.isNullOrBlank()) {
                    vm.getData3("id" to ids)
                } else {

                    vm.getData3(
                        "id" to ids,
                        "service_day" to service_day,
                        "service_time" to service_time
                    )
                }
            }

        }
        vm.getData("id" to ids)
        vm.getOrderDetail("id" to ids)

        binding.llTransferOrder.clickWithTrigger {
            val content = if (orderDetailBean?.remaining_transfer_orders_num == "0") {
                "您本月转单已用完，\n转出后将扣除${orderDetailBean?.transfer_orders_deduct_point}个服务积分"
            } else {
                "您是否将本单转出\n转出后将不再服务次单"
            }
            XPopup.Builder(this)
                .asCustom(
                    ConfirmDialog(
                        this,
                        title = "温馨提示",
                        content,
                        cancelStr = "再考虑考虑",
                        confirmStr = "确认转出",
                    ) {
                        vm.transferOrder("id" to ids)
                    })
                .show()
        }
    }

    var user_phone = ""
    var user_phone2 = ""
    var user_id9 = ""
    var cate_id = ""
    var list6 = arrayListOf<YyBean.ThirdInfo.TeamUser>()

    @SuppressLint("NotifyDataSetChanged")
    override fun startObserve() {
        // 转单
        vm.transferOrderData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                LiveEventBus.get(TransferOrderSuccess::class.java).post(TransferOrderSuccess(ids))
                finish()
            }
        }
        vm.getOrderDetailData.observeState(this) {
            onLoading { }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                orderDetailBean = it
                if (it?.remaining_transfer_orders_num == "0") {
                    binding.tvTransferOrderNum.text = "(本月转单已用完)"
                } else {
                    binding.tvTransferOrderNum.text =
                        "(本月剩余${it?.remaining_transfer_orders_num}次转单)"
                }

            }
        }
        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("确认成功")
                LiveEventBus.get<Boolean>("Qdcg2").post(true)
                finish()
            }
        }

        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                yyBean = it
                if (it != null) {
                    try {
                        if (it.second_info.size > 0) {
                            list2.clear()
                            list2.addAll(it.second_info)
                            list2[0].isCheck = 1
                            list = list2[0].timer
                            service_day = list2[0].date_timestamp


                        }
                    } catch (e: Exception) {

                    }

                    binding.apply {
                        if (it.third_info.user_status == "1") {
                            tvAdd.visible()
                        } else {
                            tvAdd.gone()
                        }
                        realName.text = it.first_info.real_name
                        storeName.text = it.first_info.store_name
                        serviceTime.text = it.first_info.service_time
                        baseAddress.text = it.first_info.base_address
                        cate_id = it.first_info.cate_id
                        user_phone = it.first_info.user_real_phone

                        if (it.first_info.is_cart_order == 1) {
                            binding?.tvServiceNum?.text =
                                "共" + it.first_info.order_goods.size + "项服务明细"
                            val list = it.first_info.order_goods
                            binding?.tvServiceNum?.click {
                                if (list.isNullOrEmpty()){
                                    return@click
                                }
                                XPopup.Builder(this@AppointmentCustomerActivity2)
                                    .asCustom(ShowServiceItemDialog(this@AppointmentCustomerActivity2, list))
                                    .show()
                            }
                        }

                        if (it.third_info.team_member.size > 0) {
                            list3.clear()
                            list6.clear()
                            list3.addAll(it.third_info.team_member)
                            list6.addAll(it.third_info.team_member)
                            if (it.third_info.user_status == "1") {
                                list3.add(YyBean.ThirdInfo.TeamUser("", "", "", "", ""))
                            }
                            adapter3.notifyDataSetChanged()
                        }
                        if (!it.third_info.team_leader.nickname.isNullOrBlank()) {
                            tvAdd.load(it.third_info.team_leader.avatar, R.mipmap.rl)
                            user_phone2 = it.third_info.team_leader.phone
                            user_id9 = it.third_info.team_leader.user_id
                            tvAdd2.visible()
                            callPhone2.visible()
                        } else {
                            tvAdd2.gone()
                            callPhone2.gone()
                        }
                        if (it.confirm_time.is_residuetime == 1) {
                            residueTime.text = "已超时"
                            residueTime.setTextColor(Color.parseColor("#F53131"))
                        } else {
                            val countDownTimer: CountDownTimer =
                                object :
                                    CountDownTimer(it.confirm_time.residue_time * 1000, 1 * 1000) {
                                    @SuppressLint("SimpleDateFormat")
                                    override fun onTick(millisUntilFinished: Long) {
                                        val s: String = formatDateTime(millisUntilFinished)
                                        //                Log.e("wy", "sysTimeStr s: "+s );
                                        residueTime.setText(s)
                                        residueTime.setTextColor(Color.parseColor("#00B7F5"))
                                    }

                                    override fun onFinish() {
                                        residueTime.setText("已超时")
                                        residueTime.setTextColor(Color.parseColor("#F53131"))
                                    }
                                }
                            countDownTimer.start()
                        }
                    }
                }
            }
        }
    }

    fun formatDateTime(milliseconds: Long): String {
        val sb = StringBuilder()
        val mss = milliseconds / 1000
        val days = mss / (60 * 60 * 24)
        val hours = mss % (60 * 60 * 24) / (60 * 60)
        val minutes = mss % (60 * 60) / 60
        val seconds = mss % 60
        val format = DecimalFormat("00")
        if (days > 0 || hours > 0) {
            sb.append(format.format(hours)).append(":").append(format.format(minutes)).append(":")
                .append(format.format(seconds))
        } else {
            sb.append("00").append(":").append(format.format(minutes)).append(":")
                .append(format.format(seconds))
        }
        return sb.toString()
    }
}